<template>
  <basic-container>
    <div class="data-statistics-container">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-card shadow="hover">
          <div class="filter-header">
            <span class="filter-title">线路信息费统计</span>
          </div>
          <div class="filter-content">
            <!-- 线路查询 -->
            <div class="filter-row">
              <div class="filter-item">
                <span class="filter-label">线路搜索：</span>
                <el-input v-model="startLocation" placeholder="选择开始地" style="width: 150px;" />
                <span style="margin: 0 8px;">至</span>
                <el-input v-model="endLocation" placeholder="选择结束地" style="width: 150px;" />
              </div>
              <div class="filter-item">
                <el-button type="primary" @click="loadChartData">查询</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </div>
            </div>
            <!-- 时间筛选 -->
            <div class="filter-row">
              <div class="filter-item">
                <span class="filter-label">时间类型：</span>
                <div class="custom-radio-group">
                  <el-button :type="dateType === 1 ? 'primary' : 'default'" size="small" @click="selectDateType(1)">
                    今日
                  </el-button>
                  <el-button :type="dateType === 2 ? 'primary' : 'default'" size="small" @click="selectDateType(2)">
                    近7天
                  </el-button>
                  <el-button :type="dateType === 3 ? 'primary' : 'default'" size="small" @click="selectDateType(3)">
                    近30天
                  </el-button>
                  <!-- <el-button :type="dateType === 4 ? 'primary' : 'default'" size="small" @click="selectDateType(4)">
                    近一年
                  </el-button> -->
                </div>
              </div>
              <div class="filter-item">
                <span class="filter-label">自定义日期：</span>
                <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                  end-placeholder="结束日期" style="width: 260px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"
                  @change="handleDateRangeChange" class="no-border-date-picker" />
              </div>
            </div>
            <!-- <div class="filter-row">
              <div class="filter-item">
                <span class="filter-label">线路类型：</span>
                <el-select v-model="routeType" placeholder="请选择线路类型" style="width: 200px;" @change="loadChartData">
                  <el-option label="全部线路" value="all"></el-option>
                  <el-option label="热门线路" value="hot"></el-option>
                  <el-option label="普通线路" value="normal"></el-option>
                </el-select>
              </div>
              <div class="filter-item">
                <el-button type="primary" @click="loadChartData">查询</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </div>
            </div> -->
          </div>
        </el-card>
      </div>

      <!-- 统计卡片 -->
      <!-- <div class="statistics-cards">
        <el-card v-for="(item, index) in statisticsCards" :key="index" class="stat-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">{{ item.title }}</span>
            <el-tooltip :content="item.description" placement="top">
              <i class="el-icon-info info-icon"></i>
            </el-tooltip>
          </div>
          <div class="card-value">
            <span class="value-number">{{ item.value }}</span>
            <span class="value-unit">{{ item.unit }}</span>
          </div>

        </el-card>
      </div> -->

      <!-- 折线图 -->
      <!-- <div class="chart-section">
        <el-card shadow="hover">
          <div class="chart-header">
            <span class="chart-title">线路信息费趋势</span>
            <div class="chart-legend">
              <span class="legend-item">
                <span class="legend-color" style="background-color: #409eff;"></span>
                <span>信息费金额</span>
              </span>
            </div>
          </div>
          <div class="chart-content">
            <div ref="chartContainer" style="height: 400px;"></div>
          </div>
        </el-card>
      </div> -->

      <!-- 数据表格 -->
      <div class="table-section">
        <el-card shadow="hover">
          <div class="table-header">
            <span class="table-title">详细数据</span>
            <el-button type="primary" size="small" @click="exportData">导出数据</el-button>
          </div>
          <el-table :data="tableData" class="data-table" border stripe>
            <el-table-column label="路线" min-width="200">
              <template slot-scope="scope">
                {{ scope.row.startText }} - {{ scope.row.endText }}
              </template>
            </el-table-column>
            <el-table-column prop="date" label="日期" min-width="150" />
            <el-table-column prop="feeAmount" label="信息费金额" min-width="120" />
            <el-table-column prop="paidUsers" label="预定人数" min-width="120" />
            <el-table-column prop="paidRoutes" label="总发行车次" min-width="120" />
            <el-table-column prop="promotion" label="推广费" min-width="120" />
            <el-table-column prop="remainPromotion" label="剩余信息费" min-width="120" />
          </el-table>
          <div class="pagination-wrapper">
            <el-pagination :current-page.sync="pagination.currentPage" :page-size.sync="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </div>
    </div>
  </basic-container>
</template>

<script>
// import * as echarts from 'echarts'
import { getLineFeeStatistics } from './api'
const XLSX = require('xlsx')

export default {
  name: "DataStatistics",
  data () {
    return {
      // 响应式数据
      dateType: 1, // 1:今日, 2:近7天, 3:近30天, 4:近一年
      dateRange: [],
      routeType: 'all',
      startLocation: '',
      endLocation: '',
      // chartInstance: null,

      // 统计卡片数据
      statisticsCards: [
        {
          title: '总信息费',
          value: '0',
          unit: '元',
          trend: 0,
          description: '统计时间段内的线路信息费总金额'
        },
        {
          title: '预定总人数',
          value: '0',
          unit: '人',
          trend: 0,
          description: '统计时间段内的预定人数'
        },
        {
          title: '总发行车次',
          value: '0',
          unit: '次',
          trend: 0,
          description: '统计时间段内的总发行车次'
        },
        {
          title: '推广费',
          value: '0',
          unit: '元',
          trend: 0,
          description: '统计时间段内的推广费总额'
        }
      ],

      // 分页数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 表格数据
      tableData: [],
      // 完整数据（用于导出）
      allData: []

      // 折线图配置
      // chartOption: {
      //   tooltip: {
      //     trigger: 'axis',
      //     backgroundColor: '#666',
      //     borderRadius: 6,
      //     padding: 12,
      //     textStyle: { color: '#fff', fontSize: 14 }
      //   },
      //   legend: {
      //     data: ['信息费金额'],
      //     right: 40,
      //     top: 10,
      //     icon: 'circle',
      //     itemWidth: 10,
      //     itemHeight: 10,
      //     textStyle: { fontSize: 14 }
      //   },
      //   grid: {
      //     left: 60,
      //     right: 30,
      //     top: 40,
      //     bottom: 30
      //   },
      //   xAxis: {
      //     type: 'category',
      //     boundaryGap: false,
      //     data: [],
      //     axisLine: { lineStyle: { color: '#e4e7ed' } },
      //     axisTick: { show: false },
      //     axisLabel: { color: '#666', fontSize: 13 }
      //   },
      //   yAxis: {
      //     type: 'value',
      //     min: 0,
      //     max: 'auto',
      //     splitNumber: 5,
      //     axisLine: { show: false },
      //     axisTick: { show: false },
      //     axisLabel: {
      //       color: '#666',
      //       fontSize: 12,
      //       formatter: function (value) {
      //         // 显示完整的数值，使用千位分隔符
      //         return value.toLocaleString();
      //       }
      //     },
      //     splitLine: { lineStyle: { color: '#e4e7ed' } }
      //   },
      //   series: [
      //     {
      //       name: '信息费金额',
      //       type: 'line',
      //       data: [],
      //       smooth: true,
      //       symbol: 'circle',
      //       symbolSize: 8,
      //       lineStyle: { color: '#409eff', width: 2 },
      //       itemStyle: { color: '#409eff', borderColor: '#fff', borderWidth: 2 },
      //       areaStyle: {
      //         color: {
      //           type: 'linear',
      //           x: 0,
      //           y: 0,
      //           x2: 0,
      //           y2: 1,
      //           colorStops: [
      //             { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
      //             { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
      //           ]
      //         }
      //       }
      //     }
      //   ]
      // }
    }
  },
  mounted () {
    // this.initChart()
    // 确保默认选中今日并加载数据
    this.$nextTick(() => {
      this.dateType = 1
      this.loadChartData()
    })
    // window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy () {
    // window.removeEventListener('resize', this.resizeChart)
    // if (this.chartInstance) {
    //   this.chartInstance.dispose()
    // }
  },
  methods: {
    // 初始化图表
    // initChart () {
    //   this.$nextTick(() => {
    //     if (this.$refs.chartContainer) {
    //       this.chartInstance = echarts.init(this.$refs.chartContainer)
    //   })
    // },

    // 模拟数据生成函数
    // generateMockData (type) {
    //   const data = []
    //   const now = new Date()

    //   if (type === 1 || type === '今日') {
    //     // 生成24小时的数据
    //     for (let i = 0; i < 24; i++) {
    //       const hour = String(i).padStart(2, '0')
    //       const feeAmount = Math.floor(Math.random() * 5000) + 1000
    //       const paidUsers = Math.floor(Math.random() * 50) + 20
    //       const avgFee = (feeAmount / paidUsers).toFixed(2)
    //       data.push({
    //         date: `${hour}:00`,
    //         feeAmount: feeAmount,
    //         paidUsers: paidUsers,
    //         avgFee: avgFee,
    //         paidRoutes: Math.floor(Math.random() * 30) + 15,
    //         conversionRate: (Math.random() * 20 + 10).toFixed(1)
    //       })
    //     }
    //   } else if (type === 2 || type === '近7天') {
    //     // 生成7天的数据
    //     for (let i = 6; i >= 0; i--) {
    //       const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    //       const dateStr = `${date.getMonth() + 1}/${date.getDate()}`
    //       const feeAmount = Math.floor(Math.random() * 5000) + 1000
    //       const paidUsers = Math.floor(Math.random() * 200) + 100
    //       const avgFee = (feeAmount / paidUsers).toFixed(2)
    //       data.push({
    //         date: dateStr,
    //         feeAmount: feeAmount,
    //         paidUsers: paidUsers,
    //         avgFee: avgFee,
    //         paidRoutes: Math.floor(Math.random() * 80) + 40,
    //         conversionRate: (Math.random() * 25 + 15).toFixed(1)
    //       })
    //     }
    //   } else if (type === 3 || type === '近30天') {
    //     // 生成30天的数据
    //     for (let i = 29; i >= 0; i--) {
    //       const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    //       const dateStr = `${date.getMonth() + 1}/${date.getDate()}`
    //       const feeAmount = Math.floor(Math.random() * 50000) + 20000
    //       const paidUsers = Math.floor(Math.random() * 400) + 200
    //       const avgFee = (feeAmount / paidUsers).toFixed(2)
    //       data.push({
    //         date: dateStr,
    //         feeAmount: feeAmount,
    //         paidUsers: paidUsers,
    //         avgFee: avgFee,
    //         paidRoutes: Math.floor(Math.random() * 150) + 80,
    //         conversionRate: (Math.random() * 30 + 20).toFixed(1)
    //       })
    //     }
    //   } else if (type === 4 || type === '近一年') {
    //     // 生成12个月的数据
    //     for (let i = 11; i >= 0; i--) {
    //       const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
    //       const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    //       const feeAmount = Math.floor(Math.random() * 200000) + 100000
    //       const paidUsers = Math.floor(Math.random() * 1000) + 500
    //       const avgFee = (feeAmount / paidUsers).toFixed(2)
    //       data.push({
    //         date: dateStr,
    //         feeAmount: feeAmount,
    //         paidUsers: paidUsers,
    //         avgFee: avgFee,
    //         paidRoutes: Math.floor(Math.random() * 300) + 200,
    //         conversionRate: (Math.random() * 35 + 25).toFixed(1)
    //       })
    //     }
    //   }

    //   return data
    // },

    // 加载图表数据
    loadChartData () {
      // 构建请求参数
      const params = {
        type: 1, // 默认按小时统计
        start_time: '',
        end_time: '',
        start_title: this.startLocation,
        end_title: this.endLocation,

      }

      // 根据日期类型设置时间范围和type参数
      if (this.dateRange && this.dateRange.length === 2) {
        // 自定义日期范围 - 按天统计

        params.start_time = this.dateRange[0].split(' ')[0] // 取日期部分
        params.end_time = this.dateRange[1].split(' ')[0]

        if (this.dateRange[0] === this.dateRange[1]) {
          params.type = 1
        } else {
          params.type = 2
        }

      } else {
        // 根据日期类型设置默认时间范围
        const now = new Date()
        if (this.dateType === 1) {
          // 今日 - 按小时统计
          params.type = 1
          const today = now.toISOString().split('T')[0]
          params.start_time = today
          params.end_time = today
        } else if (this.dateType === 2) {
          // 近7天 - 按天统计
          params.type = 2
          const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          params.start_time = sevenDaysAgo.toISOString().split('T')[0]
          params.end_time = now.toISOString().split('T')[0]
        } else if (this.dateType === 3) {
          // 近30天 - 按天统计
          params.type = 2
          const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
          params.start_time = thirtyDaysAgo.toISOString().split('T')[0]
          params.end_time = now.toISOString().split('T')[0]
        }
      }

      // 调用API接口
      getLineFeeStatistics(params).then(response => {

        if (response.data && response.err === 0) { // err 0 表示成功
          const apiData = response.data || []

          // 转换API数据格式
          const convertedData = apiData.map(item => ({
            date: item.date,
            feeAmount: parseFloat(item.amount) || 0,
            paidUsers: parseInt(item.num) || 0,
            avgFee: parseFloat(item.amount) / parseInt(item.num) || 0,
            paidRoutes: parseInt(item.count) || 0,
            conversionRate: 0, // API中没有这个字段，设为0
            startText: item.start_text,
            endText: item.end_text,
            promotion: parseFloat(item.promotion) || 0,
            remainPromotion: parseFloat(item.remain_promotion) || 0
          }))

          // 保存完整数据用于导出
          this.allData = convertedData

          // 更新统计卡片数据
          if (convertedData.length > 0) {
            const totalFeeAmount = convertedData.reduce((sum, item) => sum + item.feeAmount, 0)
            const totalPaidUsers = convertedData.reduce((sum, item) => sum + item.paidUsers, 0)
            const totalPaidRoutes = convertedData.reduce((sum, item) => sum + item.paidRoutes, 0)
            const totalPromotion = convertedData.reduce((sum, item) => sum + item.promotion, 0)

            this.statisticsCards[0].value = totalFeeAmount.toLocaleString()
            this.statisticsCards[1].value = totalPaidUsers.toLocaleString()
            this.statisticsCards[2].value = totalPaidRoutes.toLocaleString()
            this.statisticsCards[3].value = totalPromotion.toLocaleString()

            // 模拟趋势数据
            this.statisticsCards[0].trend = Math.floor(Math.random() * 20) - 10
            this.statisticsCards[1].trend = Math.floor(Math.random() * 15) - 8
            this.statisticsCards[2].trend = Math.floor(Math.random() * 25) - 12
            this.statisticsCards[3].trend = Math.floor(Math.random() * 18) - 9
          }

          // 更新分页数据
          this.updateTableData(convertedData)
        } else {
          // this.$message.error(response.data && response.data.msg ? response.data.msg : '获取数据失败')
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败，请重试')
      })
    },

    // 更新表格数据（根据分页）
    updateTableData (allData) {
      this.pagination.total = allData.length
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const endIndex = startIndex + this.pagination.pageSize
      this.tableData = allData.slice(startIndex, endIndex)
    },

    // 选择日期类型
    selectDateType (type) {
      this.dateType = type
      // 当选择tab时，清空日期区间
      this.dateRange = []
      this.loadChartData()
    },

    // 处理日期范围变化
    handleDateRangeChange () {
      if (this.dateRange && this.dateRange.length === 2) {
        // 当选择日期区间时，清空tab选中状态
        this.dateType = ''
        this.loadChartData()
      }
    },

    // 重置筛选条件
    resetFilter () {
      this.dateType = 1
      this.dateRange = []
      this.routeType = 'all'
      this.startLocation = ''
      this.endLocation = ''
      this.loadChartData()
    },

    // 导出数据
    exportData () {
      if (!this.allData || this.allData.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }

      // 定义表格列配置
      const tableHeaders = [
        { prop: 'route', label: '路线' },
        { prop: 'date', label: '日期' },
        { prop: 'feeAmount', label: '信息费金额' },
        { prop: 'paidUsers', label: '预定人数' },
        { prop: 'paidRoutes', label: '总发行车次' },
        { prop: 'promotion', label: '推广费' },
        { prop: 'remainPromotion', label: '剩余信息费' }
      ]

      // 提取表头中文名
      const header = tableHeaders.map(col => col.label)

      // 提取表头字段名
      const fields = tableHeaders.map(col => col.prop)

      // 生成数据行（使用完整数据）
      const rows = this.allData.map(item => {
        return fields.map(field => {
          let value = item[field]

          // 特殊处理路线字段
          if (field === 'route') {
            value = `${item.startText || ''} - ${item.endText || ''}`
          }

          // 对数值进行格式化
          if (field === 'feeAmount' || field === 'promotion' || field === 'remainPromotion') {
            return value ? parseFloat(value).toFixed(2) : '0.00'
          }
          return value || ''
        })
      })

      // 创建工作表
      const worksheetData = [header, ...rows]
      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)

      // 设置列宽
      const colWidths = [
        { wch: 20 }, // 路线
        { wch: 15 }, // 日期
        { wch: 12 }, // 信息费金额
        { wch: 10 }, // 预定人数
        { wch: 12 }, // 总发行车次
        { wch: 12 }, // 推广费
        { wch: 12 }  // 剩余信息费
      ]
      worksheet['!cols'] = colWidths

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, '线路信息费统计')

      // 生成文件名
      const now = new Date()
      const dateStr = now.toISOString().split('T')[0]
      const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '-')
      const fileName = `线路信息费统计_${dateStr}_${timeStr}.xlsx`

      // 下载文件
      XLSX.writeFile(workbook, fileName)
      this.$message.success(`数据导出成功，共导出 ${this.allData.length} 条记录`)
    },

    // 分页处理
    handleSizeChange (size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      // 重新加载数据以应用新的分页设置
      const mockData = this.generateMockData(this.dateType)
      this.updateTableData(mockData)
    },

    handleCurrentChange (page) {
      this.pagination.currentPage = page
      // 重新加载数据以应用新的分页设置
      const mockData = this.generateMockData(this.dateType)
      this.updateTableData(mockData)
    },

    // 图表大小调整
    // resizeChart () {
    //   if (this.chartInstance) {
    //     this.chartInstance.resize()
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
.data-statistics-container {
  padding: 20px;
  box-sizing: border-box;
}

.filter-section {
  margin-bottom: 20px;

  .el-card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  }

  .filter-header {
    margin-bottom: 16px;

    .filter-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }

  .filter-content {
    .filter-row {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .filter-item {
      display: flex;
      align-items: center;
      margin-right: 32px;

      &:last-child {
        margin-right: 0;
      }

      .filter-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
        white-space: nowrap;
      }

      .custom-radio-group {
        display: flex;

        .el-button {
          border-radius: 0;
          margin-right: -1px;

          &:first-child {
            border-radius: 4px 0 0 4px;
          }

          &:last-child {
            border-radius: 0 4px 4px 0;
            margin-right: 0;
          }
        }
      }
    }
  }
}

.statistics-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;

  .stat-card {
    flex: 1;
    min-width: 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .card-title {
        font-size: 16px;
        color: #666;
      }

      .info-icon {
        color: #bbb;
        font-size: 16px;
        cursor: pointer;
      }
    }

    .card-value {
      display: flex;
      align-items: baseline;
      margin-bottom: 8px;

      .value-number {
        font-size: 28px;
        font-weight: bold;
        color: #333;
        margin-right: 4px;
      }

      .value-unit {
        font-size: 14px;
        color: #999;
      }
    }


  }
}

.chart-section {
  margin-bottom: 20px;

  .el-card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  }

  .chart-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;

    .chart-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .chart-legend {
      display: flex;
      align-items: center;

      .legend-item {
        display: flex;
        align-items: center;
        margin-left: 16px;

        .legend-color {
          width: 12px;
          height: 12px;
          border-radius: 2px;
          margin-right: 6px;
        }

        span {
          font-size: 13px;
          color: #666;
        }
      }
    }
  }
}

.table-section {
  .el-card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  }

  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;

    .table-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }

  .data-table {
    margin-bottom: 16px;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
}

// 去掉日期选择器内部输入框的边框
:deep(.no-border-date-picker) {
  .el-range-input {
    border: none !important;
    background: transparent !important;
  }

  .el-range-separator {
    border: none !important;
  }

  .el-range__icon {
    border: none !important;
  }
}
</style>